<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\model\User;
use app\common\controller\Frontend;
use EasyWeChat\MiniApp\Application;
use think\facade\Log;
class Mpwechat extends Frontend{

    protected array $noNeedLogin = ['sessioncode','login','notice','config','noticedetail'];
    protected $mpApp;

    public function initialize(): void
    {
        parent::initialize();
        $config = [
            'app_id' => 'wx8bb452105c23ec23',
            'secret' => 'e9dd35243f455d23539da568d749c4ef',
            'http' => [
                'throw'  => true, 
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ];
        $this->mpApp = new Application($config);
    }

    public function sessioncode(){
        if($this->request->isPost()){
            $code = $this->request->post('code','');
                $utils = $this->mpApp->getUtils();
                $response = $utils->codeToSession($code);
                Log::info(json_encode($response,1));
                $user = User::where('openid', $response['openid'])->find();
                $userinfo = [];
                if($user){
                    if($user->group_id > 1){
                        $this->auth->direct($user['id']);
                        $userinfo = $this->auth->getUserInfo();
                        
                    }
                }else{
                    User::create(
                        ['unionid'=>$response['unionid'],'openid'=>$response['openid'],'username'=>md5($response['openid']),'password'=>md5($response['openid']),'salt'=>rand(100000,999999),'group_id'=>1],
                        ['openid','username','password','salt','unionid']
                    );
                }
                $this->success('',['openid'=>$response['openid'],'userinfo'=>$userinfo],200);
        }
    }

    public function login(){
        if($this->request->isPost()){
            $code = $this->request->post('code','');
            $openid = $this->request->post('openid','');
            $avatar = $this->request->post('avatar','');
            $api = $this->mpApp->getClient();
            $response = $api->postJson('/wxa/business/getuserphonenumber', [
                "code" => $code,
            ])->toArray();
            $user = User::where('openid', $openid)->find();
            $user->avatar = $avatar;
            $user->mobile = $response['phone_info']['purePhoneNumber'];
            $user->nickname = mb_substr($response['phone_info']['purePhoneNumber'],0,3).'****'.mb_substr($response['phone_info']['purePhoneNumber'],7,4);
            if($user->group_id<2){
                $user->group_id = 2;
            }else{

            }
            $user->save();
            $this->auth->direct($user['id']);
            $userinfo = $this->auth->getUserInfo();
            $this->success('',$userinfo,200);
        }
    }
    public function userinfo(){
        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $this->error('',[],201);
        }

        $this->success('',$user,200);
    }

    public function config(){
        if($this->request->isPost()){
            $type = $this->request->post('type');
            $data = [];
            foreach (explode(',',$type) as $value) {
                $data[$value] = get_sys_config($value);
            }
        }
        $this->success('',$data,200);
    }

    public function notice(){
       $list =  Db::name('Notice')->where('status',1)->order('weigh desc')->limit(3)->field('title,id')->select();
       $this->success('',$list,200);
    }
    public function noticedetail(){
        $id = $this->request->param('id');
        $list =  Db::name('Notice')->where('id',$id)->find();
       $this->success('',$list,200);
    }

}